package cn.wizzer.modules.controllers.platform.customer;

import cn.wizzer.common.annotation.SLog;
import cn.wizzer.common.base.Result;
import cn.wizzer.common.filter.PrivateFilter;
import cn.wizzer.common.page.DataTableColumn;
import cn.wizzer.common.page.DataTableOrder;
import cn.wizzer.modules.models.customer.Customer;
import cn.wizzer.modules.models.store.Store;
import cn.wizzer.modules.models.store.Store_dispatch;
import cn.wizzer.modules.models.store.Store_middle;
import cn.wizzer.modules.models.sys.Sys_role;
import cn.wizzer.modules.models.sys.Sys_user;
import cn.wizzer.modules.services.customer.CustomerService;
import cn.wizzer.modules.services.store.StoreDispatchService;
import cn.wizzer.modules.services.store.StoreMiddleService;
import cn.wizzer.modules.services.store.StoreService;
import cn.wizzer.modules.services.sys.SysUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@IocBean
@At("/platform/customer/customer")
@Filters({@By(type = PrivateFilter.class)})
public class CustomerController {
	private static final Log log = Logs.get();
	@Inject
	private CustomerService customerService;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private StoreService storeService;
	@Inject
	private StoreDispatchService storeDispatchService;

	@At("")
	@Ok("beetl:/platform/customer/customer/index.html")
	@RequiresAuthentication
	public void index() {

	}

	@At("/library")
	@Ok("beetl:/platform/customer/customer/libraryIndex.html")
	@RequiresAuthentication
	public void library() {

	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns,@Param("..") Customer customer) {
		Cnd cnd = Cnd.NEW();
		Subject subject = SecurityUtils.getSubject();
		Sys_user user = (Sys_user) subject.getPrincipal();
		String code=null;
		List<Sys_role> list=user.getRoles();
		code=list.stream().filter(p -> p.getCode().equals("sysadmin"))
				.findFirst()
				.map(p->p.getCode()).orElse(null);
		if(code==null){ cnd.and("opBy","=",user.getId());}

		if(!Strings.isBlank(customer.getCompanyName())){
			cnd.and("companyName","like","%"+customer.getCompanyName()+"%");
		}
		if(!Strings.isBlank(customer.getContactsName())){
			cnd.and("contactsName","like","%"+customer.getContactsName()+"%");
		}
		cnd.and("state","=",customer.getState());
    	return customerService.data(length, start, draw, order, columns, cnd, null);
    }

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object publicData(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns,@Param("..") Customer customer) {
		Cnd cnd = Cnd.NEW();
		if(!Strings.isBlank(customer.getCompanyName())){
			cnd.and("companyName","like","%"+customer.getCompanyName()+"%");
		}
		if(!Strings.isBlank(customer.getContactsName())){
			cnd.and("contactsName","like","%"+customer.getContactsName()+"%");
		}
		cnd.and("state","=",customer.getState());
		return customerService.data(length, start, draw, order, columns, cnd, null);
	}

    @At
    @Ok("beetl:/platform/customer/customer/add.html")
    @RequiresAuthentication
    public void add() {

    }

    @At
    @Ok("json")
    @SLog(tag = "新建Customer", msg = "")
    public Object addDo(@Param("..") Customer customer, HttpServletRequest req) {
		try {
			customer.setState(1);//设置意向客户
			customerService.insert(customer);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }

    @At("/edit/?")
    @Ok("beetl:/platform/customer/customer/edit.html")
    @RequiresAuthentication
    public Object edit(String id) {
		return customerService.fetch(id);
    }

    @At
    @Ok("json")
    @SLog(tag = "修改Customer", msg = "ID:${args[0].id}")
    public Object editDo(@Param("..") Customer customer, HttpServletRequest req) {
		try {

			customer.setOpAt((int) (System.currentTimeMillis() / 1000));
			customerService.updateIgnoreNull(customer);
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


	@At({"/toPublic","/toPublic/?"})
	@Ok("json")
	@SLog(tag = "转入公共库", msg = "ID:${args[0])}")
	public Object toPublic(String id) {
		try {
			Customer customer=customerService.fetch(id);
			customer.setOldopBy(customer.getOpBy());
			customer.setState(3);
			customer.setOpBy(null);
			customerService.update(customer);
			/*customerService.update(Chain.make("oldopBy",customer.getOpBy()),Cnd.where("id","=",customer.getId()));
			customerService.update(Chain.make("opBy",""),Cnd.where("id","=",customer.getId()));*/
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

    @At({"/delete","/delete/?"})
    @Ok("json")
    @SLog(tag = "删除Customer", msg = "ID:${args[2].getAttribute('id')}")
    public Object delete(String id, @Param("ids") String[] ids ,HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				customerService.delete(ids);
    			req.setAttribute("id", org.apache.shiro.util.StringUtils.toString(ids));
			}else{
				customerService.delete(id);
    			req.setAttribute("id", id);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
    }


    @At("/detail/?")
    @Ok("beetl:/platform/customer/customer/detail.html")
    @RequiresAuthentication
	public Object detail(String id) {
		if (!Strings.isBlank(id)) {
			Customer customer=customerService.fetch(id);
			if(customer.getState()==3){
				customer.setNickName(sysUserService.fetch(customer.getOldopBy()).getNickname());
			}
			return customer;
		}
		return null;
    }


	@At({"/knotOrder","/knotOrder/?"})
	@Ok("json")
	@SLog(tag = "结单", msg = "ID:${args[2].getAttribute('id')}")
	public Object toPublic(String id, @Param("ids") String[] ids , HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				for(String i:ids){
					Customer customer=customerService.fetch(i);
					customer.setState(4);
					customerService.update(customer);
					//存入运营经理、销售经理分单
					Store  store=new Store();
					BeanUtils.copyProperties(store,customer);
					store=storeService.insert(store);
					Store_dispatch storeDispatch=new Store_dispatch();
					storeDispatch.setStoreId(store.getId());
					storeDispatch.setState(0);
					storeDispatch.setCode("operate_leader");
					storeDispatchService.insert(storeDispatch);
					storeDispatch.setCode("sale_leader");
					storeDispatchService.insert(storeDispatch);
				}
				req.setAttribute("id", org.apache.shiro.util.StringUtils.toString(ids));
			}else{
				Customer customer=customerService.fetch(id);
				customer.setState(4);
				customerService.update(customer);
			}
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At({"/crawl","/crawl/?"})
	@Ok("json")
	@SLog(tag = "url爬取", msg = "ID:${args[1].getAttribute('customer')}")
	public Object toPublic(String url, HttpServletRequest req) {
		try {
			if(Strings.isBlank(url)){
				Result.error("system.error");
			}
			Document doc = Jsoup.connect(url)
					.userAgent("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)") // 设置 User-Agent
					.timeout(30000).get();
			Elements es = doc.getElementsByTag("body").select("div.content-wrap").select("div.fd-clr");

			Elements h1=es.select("div.contact-info");

			Elements parent=h1.get(0).children();
			String companyName=parent.get(0).text();
			String contactsName=parent.get(1).text().split("：")[1].replaceAll("免费电话","");

			Elements p= es.select("div.fd-line").get(0).children();
			Elements desc=p.get(1).children();
			String telphone=desc.get(0).child(1).text();
			String mobile=desc.get(1).child(1).text();
			String address=desc.get(3).child(1).text();
			String website=desc.get(5).child(1).getElementsByTag("a").text();
			Customer customer=new Customer();
			customer.setCompanyName(companyName);
			customer.setContactsName(contactsName);
			customer.setTelphone(telphone);
			customer.setWebsite(website);
			customer.setMobile(mobile);
			customer.setWebsite(website);
			customer.setAddress(address);
			req.setAttribute("customer",customer);
			return customer;
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
}
